var Chat = {
    go2chat: function(pos) {
        var chatDetail = GetLS("chat_list")[pos];
        if (CurrentUser._id == chatDetail.to)
            chatDetail._id = chatDetail.from;
        else
            chatDetail._id = chatDetail.to;
        SetLS("chat_detail", chatDetail);
        OpenNewWin("chat_detail");
    },
    listInit: function() {
        $ajax({
            url: "/message/list",
            data: CurrentUser,
            success: function(res) {
                var items = res.result;
                SetLS("chat_list", items);
                var html = "";
                var length = items && items.length || 0;
                var de=CurrentUser.category==30?"删除":"Delete";
                var ubbClass = "";
                if (!items||items.length==0||items==undefined){
                        html += '<div class="umt_15">'+
                                        '<div class="tx-c">'+(CurrentUser.category==30?"亲,你还没有和好友聊天的记录哦!o(︶︿︶)o":"Pro, you haven't had a chat with your friends")+'</div>'+
                                '</div>';
                    }
                for (var i=0; i<length; i++) {
                    if (items[i].media == 1)
                        items[i].content = "[ 图片 ]";
                    html += '<div class="ub up_list uml_1f" ontouchstart="zy_touch()" onclick="Chat.go2chat(\''+ i +'\')">'+
                            '    <div class="uh2p8 uw2h8 uc-ap50 ub_img_cover detailEvt" style="background-image:url('+ Core.id2url(items[i]) +')"></div>'+
                            '    <div class="ub-f1 ub ub-ver upl_p5">'+
                            '        <div class="ub-f1 ub" id="from" data-fr="'+items[i].from+'" type="hidden">'+
                            '            <div class="ub-f1 ub_left" id="to" data-to="'+items[i].to+'" type="hidden">'+ items[i].name +'　'+ (items[i].sex?items[i].sex:'') +'</div>'+
                            '        </div>'+
                            '        <div class="ub_left ub-f1">'+ (items[i].content?items[i].content:"这个家伙很懒，什么也没留下。") +'</div>'+
                            '    </div>'+
                            '    </div>'+
                            '    <div id="btnCtn" class="ub_right">'+
                            '      <div id="deldata" data-fr="'+items[i].from+'" data-to="'+items[i].to+'" data-ontouchstart="zy_touch()" onclick="Chat.remove();" class="btn uw3 umr_p2 ub_right ufp6 bc_base t-wh umt_8f">'+de+'</div>'+
                            '    </div>';
                }
                $("#ctn").html(html);
                Friend.initMessage();
            }
        });
    },
    openChatWin: function() {
        $("#sendCtn").removeClass("hide");
        Zycon("chat_detail_content", $("#header").outerHeight());
    },
    detailInit: function() {
        var toObj = GetLS("chat_detail");
        var data = {};
        data.from = CurrentUser._id;
        data.to = toObj.id?toObj.id:toObj._id;

        var ajaxAfterFun = function(items, user){
            // setTimeout(tmoFun, 1000*2);
            var html = Chat.gnHtml(items, user);
            $("#ctn").append(html);
            if (html != "")
                $(document).scrollTop($(document).height());
        }
        var tmoFun = function(){
            $ajaxT({
                url: "/message/detail",
                data: data,
                success: function(res) {
                    ajaxAfterFun(res.result, toObj);
                }
            });
        };
        tmoFun();
    },
    send: function() {
        var msgcontent = $("#msg").val();
        if (msgcontent == "") {
            (CurrentUser.category==30?$alert("留言内容不能为空"):$alertEn("The message can not be empty"));
            return;
        }
        $("#msg").val("");

        var toObj = GetLS("chat_detail");
        var data = {};
        data.from = CurrentUser._id;
        data.to = toObj.id?toObj.id:toObj._id;
        data.media = 0;
        data.content = msgcontent;

        $ajax({
            url: "/message/add",
            data: data,
            success: function(res) {
                CCall("Chat.sendAppend('" + JSON.stringify(res.result) + "')");
            }
        });
    },
    sendPhoto: function() {
        Upload.init(Core.API_VER + "/upload?compress=1", function(res) {
            res = res[0];
            if (res.code) {
                $alert(res.codemsg);
                return;
            }

            var toObj = GetLS("chat_detail");
            var data = {};
            data.from = CurrentUser._id;
            data.to = toObj._id;
            data.media = 1;
            data.content = res.result.url;

            $ajax({
                url: "/message/add",
                data: data,
                success: function(res) {
                    Chat.sendAppend(JSON.stringify(res.result));
                }
            });
        });
    },
    sendAppend: function(item) {
        item = JSON.parse(item);
        var html = Chat.gnHtml(new Array(item), "self");
        $("#ctn").append(html);
        if (html != "")
            $(document).scrollTop($(document).height());
    },
    gnHtml: function(items, user) {
        var html = "";
        var flag = false;
        if (Chat.lastID && user != "self")
            flag = true;
        for (var i = 0; i < items.length; ++i) {
            if (flag) {
                if (items[i]._id == Chat.lastID)
                    flag = false;
                continue;
            }
            var content = "";

            if (items[i].from == CurrentUser._id) {
                if (items[i].media == 0 ) {
                    content = ' <div class="talk_ctn" style="float:right">' +
                                '       <div class="uc-a upp5 wb_a talk_ctn right umw3 uml_2" style="float:none;" ontouchstart="zy_touch(\'talk_ctn_act\', undefined, \'longpress\')" onclick="Appcan.copy(\''+ items[i].mcontent +'\');">' +
                                '           <div class="uwp5 uh1 ub_img im_talk_right"></div>' + items[i].content +
                                '       </div>' +
                                '   <div class="ufp8 tx-r">' + Core.offsetDate(items[i].create) + '</div>' +
                                '</div>';
                }else if (items[i].media == 1) {
                    content = '<div class="uw7 uh5 ub_img photoBrowserEvent" data-url="'+ items[i].content +'" style="background-image:url('+ Core.id2url(items[i].content, "thumbnail") +'); background-size:cover; float:right" ontouchstart="zy_touch()" onclick="ImageBrowser(\'' + items[i].content + '\')"></div>';
                }
                html += '<div class="ub-f1 ub uptb_p5">' +
                    '    <div class="uw3"></div>' +
                    '    <div class="ub-f1 upr_1">' + content +
                    '    </div>' +
                    '    <div class="uh4 uw3h8 uc-ap50 umar-tp5 ub_img_cover  uc-a umr_p2" style="background-image:url(\'' + Core.id2url(CurrentUser) + '\');"></div>' +
                    '</div>';
            } else {
                if (items[i].media == 0&&CurrentUser.category==20) {
                    content = '<div class="talk_ctn">' +
                              '     <div class="ub uc-a upp5 wb_a talk_ctn left umw3 umar-r2" style="" ontouchstart="zy_touch(\'talk_ctn_act\', undefined, \'longpress\')" onclick="Appcan.copy(\''+ items[i].content +'\');">' +
                              '         <div class="uwp5 uh1 ub_img im_talk_left"></div>' + items[i].content +
                              '         <div class="ub-img im_icon_translate-t uw1p5 uh1p5 ump05" ontouchstart="zy_touch()" onclick="Chat.translate(\'' + items[i].content + '\')"></div>' + 
                              '     </div>' +
                              '     <div id="fanyi" class="ufp8"></div>' + 
                              '     <div class="ufp8 tx-l">' + Core.offsetDate(items[i].create) + '</div>' +
                              '</div>';
                }else if(items[i].media == 0 &&CurrentUser.category==30){
                   content = '<div class="talk_ctn">' +
                              '     <div class="ub uc-a upp5 wb_a talk_ctn left umw3 umar-r2" style="" ontouchstart="zy_touch(\'talk_ctn_act\', undefined, \'longpress\')" onclick="Appcan.copy(\''+ items[i].content +'\');">' +
                              '         <div class="uwp5 uh1 ub_img im_talk_left"></div>' + items[i].content +
                              '         <div class="ub-img im_icon_translate uw1p5 uh1p5 ump05" ontouchstart="zy_touch()" onclick="Chat.translate(\'' + items[i].content + '\')"></div>' + 
                              '     </div>' +
                              '     <div id="fanyi" class="ufp8"></div>' + 
                              '     <div class="ufp8 tx-l">' + Core.offsetDate(items[i].create) + '</div>' +
                              '</div>'; 
                }else if (items[i].media == 1) {
                    content = '<div class="uw7 uh5 ub_img photoBrowserEvent" data-url="'+ items[i].content +'" style="background-image:url('+ Core.id2url(items[i].content, "thumbnail") +'); background-size:cover;" ontouchstart="zy_touch()" onclick="ImageBrowser(\'' + items[i].content + '\')"></div>';
                }
                html += '<div class="ub-f1 ub uptb_p5">' +
                    '    <div class="uh4 uw3h8 uc-ap50 uml_p2 umar-tp5 ub_img_cover  uc-a" style="background-image:url(\'' + Core.id2url(GetLS("chat_detail")) + '\');"></div>' +
                    '    <div class="ub-f1 upl_1">' + content +
                    '    </div>' +
                    '    <div class="uw3"></div>' +
                    '</div>';
            }
        }
        if (items[items.length-1] != undefined)
            Chat.lastID = items[items.length-1]._id;
        return html;
    },
    translate: function(str){
        var $this = $(event.currentTarget);
        event.stopPropagation();
        $ajax({
            url: "/fanyi",
            data:{
                content: str
            },
            success: function(res){
                $this.parent().next("#fanyi").text(res.result.result);
            }
        });
    },
    remove: function() {
        var $this = $(event.currentTarget);
        uexWindow.confirm(CurrentUser.category==30?"警告":"Warning",CurrentUser.category==30?"确定要删除吗？":"Do you want to detete?",CurrentUser.category==30?"确定,取消":"Sure,Cancel");
            function cbConfirm(opId, dataType, ensure){
            if(ensure == 0){
                var fr = $this.data("fr");
                var to = $this.data("to");
                $ajax({
                    url: "/message/remove",
                    data: {
                        fid:fr,
                        uid:to
                        },
                    success: function(res) {
                        if(res.code)
                            return $alert(res.codemsg);
                        var ml=CurrentUser.category==30?"ch/":"en/";
                        PCall("../"+ml+"chat","CCall('Chat.listInit()')");
                    }
                });
                
          }
        }
        uexWindow.cbConfirm = cbConfirm; 
    },
}